<?php

namespace app\admin\controller;

use support\Request;
use support\Response;
use Exception;
use app\model\MemberModel;
use app\model\CardUserModel;
use app\model\CardModel;
use app\model\CompanyModel;
use app\model\AddressModel;
use app\model\BizPayRecordModel;
use app\model\BizGoodsOrderModel;
use app\model\OrderModel;

class MemberController {

    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            
            $query = MemberModel::query()
                ->whereNotNull('phone')
                ->orderBy('id', 'desc');


            // 手机号查询
            $phone = $request->get('phone', '');
            if ($phone) {
                $query->where('phone', 'like', '%' . $phone . '%');
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                $item['vip_at'] = empty($item->vip_at) ? '-' : date('Y-m-d H:i:s', $item->vip_at);
                
                // 计算会员卡云豆总数
                $cardScoreTotal = CardUserModel::where('user_id', $item->id)
                    ->where('status', 1) // 只统计有效的卡片
                    ->sum('score');
                $item['card_score_total'] = round($cardScoreTotal, 2);
                
                // 获取所属公司信息（通过卡片关联）
                $cardUser = CardUserModel::where('user_id', $item->id)
                    ->where('status', 1)
                    ->first();
                
                if ($cardUser) {
                    $card = CardModel::find($cardUser->card_id);
                    if ($card && $card->company_id) {
                        $company = CompanyModel::find($card->company_id);
                        $item['company_name'] = $company ? $company->name : '-';
                        $item['company_id'] = $card->company_id;
                    } else {
                        $item['company_name'] = '-';
                        $item['company_id'] = null;
                    }
                } else {
                    $item['company_name'] = '-';
                    $item['company_id'] = null;
                }

                $item['address_total'] = AddressModel::where('user_id', $item->id)->count();
                
                // 添加黑名单状态文本
                $item['in_black_text'] = $this->getBlackStatusText($item->in_black ?? 0);

                // 随心付消费
                $item['biz_pay_record_total_money'] = BizPayRecordModel::where([
                    ['user_id','=',$item->id],
                    ['pay_status','=',1],
                ])->sum('pay_money');
                $item['biz_pay_record_total_money'] = $item['biz_pay_record_total_money'] ?? 0;

                // 商家订单总额
                $item['biz_order_total_money'] = BizGoodsOrderModel::where([
                    ['user_id','=',$item->id],
                    ['status','=','pay'],
                ])->sum('pay_money');
                $item['biz_order_total_money'] = $item['biz_order_total_money'] ?? 0;

                // 严选消费金额
                $item['order_total_money'] = OrderModel::where([
                    ['user_id','=',$item->id],
                    ['pay_status','=','1'],
                ])->sum('pay_amount');
                $item['order_total_money'] = $item['order_total_money'] ?? 0;
            }

            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新用户黑名单状态
     * @param Request $request
     * @return Response
     */
    public function updateBlackStatus(Request $request): Response
    {
        try {
            $userId = (int)$request->post('user_id');
            $inBlack = (int)$request->post('in_black');

            if (!in_array($inBlack, [0, 1, 2])) {
                throw new Exception('无效的黑名单状态');
            }

            $user = MemberModel::find($userId);
            if (!$user) {
                throw new Exception('用户不存在');
            }

            $user->in_black = $inBlack;
            $user->updated_at = time();
            $user->save();

            return json([
                'data' => null,
                'msg' => '黑名单状态更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取黑名单状态文本
     * @param int $inBlack
     * @return string
     */
    private function getBlackStatusText(int $inBlack): string
    {
        switch ($inBlack) {
            case 0:
                return '正常';
            case 1:
                return '禁言';
            case 2:
                return '禁止下单';
            default:
                return '未知状态';
        }
    }

    /**
     * 更新用户是否是配货员
     * @param Request $request
     * @return Response
     */
    public function updateExpressSendUser(Request $request): Response
    {
        try {
            $userId = (int)$request->post('user_id');

            $user = MemberModel::find($userId);
            if (!$user) {
                throw new Exception('用户不存在');
            }

            $user->is_store_worker = $user->is_store_worker == 1 ? 0 : 1;
            $user->updated_at = time();
            $user->save();

            return json([
                'data' => null,
                'msg' => '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
